const { Hash } = require('crypto');
const express = require('express')
const uploader = require('express-fileupload');
const { existsSync, promises:{appendFile, writeFile} } = require('fs');
const { resolve, extname } = require('path');
const { number } = require('prop-types');
const app = express()
app.use(express.json())
app.use(express.urlencoded(
    { urlencoded: true }))
app.use(uploader())
app.get('/', (req, res) => {
    res.send('hello')
})
app.post('/api/upload', async (req, res) => {
    //解决node跨域问题加的
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Credential', 'true');
    res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
    res.setHeader('Content-Type', "application/json; charset=utf-8");
    const { name, size, type, offset, hash } = req.body
    console.log( req.body,name, size, type, offset, hash)
    const { file } = req.files
    console.log(file,212121121)
    const ext = extname(name)
    // console.log(ext)
    const fileName = resolve(__dirname, `./public/${hash}${ext}`)
    // console.log(fileName,121,existsSync(fileName),offset)
    console.log(offset,Boolean(offset),Number(offset),11111)
    if (Number(offset)) {
        if (!existsSync(fileName)) {
            res.status(400).send({ message: "不存在" })
            return
        }
        await appendFile(fileName, file.data)
        res.send({
            data: 'appended'
        })
        return

    }
    await writeFile(fileName, file.data);
    res.send({
      data: 'created',
    });
})
app.listen(3000, () => {
    console.log('启动成功')
})